#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "mystdio.h"
#include <stdlib.h>
#include <unistd.h>
File* BuyFile(int fd ,int flag)
{
    File* f = (File*)malloc(sizeof(File));
    if(f == NULL)
        return NULL;
    f->fileno = fd;
    f->flag = flag;
    f->bufferlen = 0;
    f->flush_method = LINE_FLUSH;
    memset(f->outbuffer,0,sizeof(f->outbuffer));
    return f;
}


File* MyFopen(char* path,char* mode)
{
    int fd = -1;
    int flag = 0;
    if(!strcmp(mode,"w"))
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path,flag,0666);
    }
    else if (!strcmp(mode,"a"))
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path,flag,0666);
    }
    else if (!strcmp(mode,"r"))
    {
        flag = O_RDONLY;
        fd = open(path,flag);
    }
    else 
    {
        return NULL;
    }
    if(fd < 0 ) return NULL;
    else 
        return BuyFile(fd,flag);
}

void MyFclose(File* file)
{

}

int MyFwrite(File* file,void *str,int len)
{
    memcpy(file->outbuffer+file->bufferlen,str,len);
    file->bufferlen += len;
    if(file->flush_method == LINE_FLUSH && file->outbuffer[file->bufferlen - 1] == '\n')
    {
        MyFllush(file);
    }
    return 0;
}

void MyFllush(File* file)
{
    write(file->fileno,file->outbuffer,file->bufferlen);
    file->bufferlen = 0;
}
